package com.lucenly.spell.base

import com.moregold.mvvmlib.entity.BaseResult
import okhttp3.Response
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import java.io.IOException
import java.lang.reflect.Type

/**
 *  Created by Yang on 2020/12/17 0017 10:07.
 *自定义解析器，并用@Parser注解标注，最后由注解处理器rxhttp-compiler自动生成的
 */
@Parser(name = "Response")
open class ResponseParser<T> : AbstractParser<T> {

    //以下两个构造方法是必须的
    protected constructor() : super()
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        val type: Type = ParameterizedTypeImpl[BaseResult::class.java, mType] //获取泛型类型
        val data: BaseResult<T> = convert(response, type)   //获取Response对象
        val t = data.data//获取data字段
        if ((data.status != 0 &&data.status != 200) || t == null) { //code不等于200，说明数据不正确，抛出异常
            throw ParseException(data.status.toString(), data.msg, response)
        }
        return t
    }
}